<template>
	<div class="padding-across-10" v-loading.fullscreen.lock="loading" element-loading-text="拼命加载中">
		<div class="flex-inline">
			<headerOpreate :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
		</div>
		<div>
			<div style="float: left">
				<span style="font-size: 13px;font-weight: bold">区域</span>
				<el-cascader v-model="cascaderId" size="small" style="width:100px;margin-right: 	5px"
				:options="cascaderDatas"
				change-on-select
				:show-all-levels="false"
				:props="defaultCascaderProps"
				@change="selectDistrict">
			</el-cascader>

			<span style="font-size: 13px;font-weight: bold">检索字段</span>
			<el-select size="small" v-model="value" placeholder="请选择查询方式" style="width: 80px;margin-right: 2px" @change="selectType">
				<el-option label="编号" :value="0"></el-option>
				<el-option label="标签" :value="1"></el-option>
				<el-option label="描述" :value="2"></el-option>
			</el-select>
			<span style="font-size: 13px;font-weight: bold">关键字</span>
			<el-input size="small" style="width: 160px;" class="inline-input" v-model="searchModel" :placeholder="contentHint">
				<el-button id="searchData" slot="append" icon="search" @click="getDatas"></el-button>
			</el-input>
		</div>
		<div class="block" style="text-align:right;float: right">
			<el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange" :current-page="currentPage" :page-size="pageSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="totalSize">
			</el-pagination>
		</div>
	</div>
	<el-table border style="width: 100%;" @selection-change="handleSelectionChange" :data="tableData">
		<el-table-column :show-overflow-tooltip="true" type="selection" align="center" width="50px"></el-table-column>
		<el-table-column :show-overflow-tooltip="true" label="编号" align="center" prop="code"></el-table-column>
		<el-table-column :show-overflow-tooltip="true" label="标签" align="center" prop="tag"></el-table-column>
		<el-table-column :show-overflow-tooltip="true" label="创建人" align="center" prop="uid"></el-table-column>
		<el-table-column :show-overflow-tooltip="true" label="所属区域" align="center" prop="district">
			<template slot-scope="scope">
				<span v-if="scope.row.district != null">{{scope.row.district}}</span>
				<el-tag type="danger" v-else>暂未绑定</el-tag>
			</template>
		</el-table-column>
		<el-table-column :show-overflow-tooltip="true" label="创建时间" align="center" prop="time" width="200"></el-table-column>
		<el-table-column :show-overflow-tooltip="true" label="描述" align="center" prop="Desc"></el-table-column>
		<el-table-column :show-overflow-tooltip="true" :label="$t('message.operation')" align="center" width="250">
			<template slot-scope="scope">
					<!-- <a style="text-decoration:none;cursor: pointer;color :#20A0FF" @click="editShelf(scope.row)"><i class="el-icon-edit"></i>编辑</a>
					<a style="text-decoration:none;cursor: pointer;color :#20A0FF" @click="shelfBook(scope.row)"><i class="el-icon-eleg-icon_book"></i>书籍</a>
					<a style="text-decoration:none;cursor: pointer;color :#20A0FF" @click="setPosition(scope.row)"><i class="el-icon-eleg-icon_pin"></i>位置</a> -->
					<el-button @click="editShelf(scope.row)" type="primary" size="small"><i class="el-icon-edit el-icon--left"></i>编辑</el-button>
					<el-button @click="shelfBook(scope.row)" type="primary" size="small"><i class="el-icon-eleg-icon_book el-icon--left"></i>书籍</el-button>
					<el-button @click="setPosition(scope.row)" type="primary" size="small"><i class="el-icon el-icon-eleg-icon_pin el-icon--left"></i>位置</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="block" style="text-align: right; margin-bottom: 100px;">
			<el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange" :current-page="currentPage" :page-size="pageSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="totalSize">
			</el-pagination>
		</div>
		<!--创建层架弹框-->
		<el-dialog title="创建层架" v-model="createShelfDialog" :show-close="false" :class="[dialog-tiny-width]">
			<el-form id="form" ref="createShelfForm" :model="createShelfForm" :rules="createRules" label-width="100px">
				<el-form-item label="编号" prop="code">
					<el-input v-model="createShelfForm.code" required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="标签" prop="tag">
					<el-input v-model="createShelfForm.tag" required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="Desc">
					<el-input v-model="createShelfForm.Desc" required style="max-width:480px"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="createShelfDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmCreate('createShelfForm')">确 定</el-button>
			</div>
		</el-dialog>
		<!--编辑层弹出框-->
		<el-dialog title="修改层架信息" v-model="editShelfDialog" :show-close="false" :class="[dialog-tiny-width]">
			<el-form id="form" ref="editShelfForm" :model="editShelfForm" :rules="createRules" label-width="100px">
				<el-form-item label="标签" prop="tag">
					<el-input v-model="editShelfForm.tag" disabled required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="编号" prop="code">
					<el-input v-model="editShelfForm.code" required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="Desc">
					<el-input v-model="editShelfForm.Desc" required style="max-width:480px"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="editShelfDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmEdit('editShelfForm')">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 绑定区域 -->
		<el-dialog title="批量绑定区域" v-model="bindDistrictDialog" :class="[dialog-tiny-width]">
			<el-tree :show-overflow-tooltip="true" style="height: 300px;overflow: auto;padding-left: 15px" ref="tree" :data="districtsDatas" :props="defaultProps" node-key="DistrictKeyId" :current-node-key="currentNodeKey" :highlight-current="true" :default-expanded-keys="defaultExpandedKeys" @node-click="handleNodeClick">
			</el-tree>
			<div slot="footer" class="dialog-footer">
				<el-button @click="bindDistrictDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmBind()">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import $ from 'jquery'
	import { GloabFun, HttpServer } from '../../../../assets/js/common.js'
	import headerOpreate from '../../../../components/headerOpreate'
	let id = 1000;
	export default {
		components: {
			headerOpreate
		},
		data() {
			//回车触发查询按钮
			document.onkeydown = function(event) {
				var e = event || window.event;
				if(e && e.keyCode == 13) { //回车键的键值为13
					$("#searchBookData").click(); //调用登录按钮的登录事件
				}
			};
			return {
				idReload: false,
				loading: false,
				tableData: [],
				createShelfDialog: false,
				editShelfDialog: false,
				bindDistrictDialog: false,//绑定区域
				districtsDatas: [],
				defaultExpandedKeys: [],
				defaultProps: {
					children: 'Children',
					label: 'Name',
					id: 'Id'
				},
				currentNodeKey: null,

				//区域下拉框属性
				defaultCascaderProps: {
					children: 'Children',
					label: 'Name',
					value: 'DistrictKeyId'
				},
				cascaderDatas: [],
				cascaderId: [],
				selectDistrictId: null,
				value: 0, //搜索
				searchModel: '',
				contentHint: '层架编号 查询',
				opreateDatas: [
				{
					size: "small",
					type: 'primary',
					icon: 'el-icon-eleg-icon_refresh el-icon--left',
					name: '刷新',
					action: 'reloadDatas'
				},
					// {
					// 	show: GloabFun.getUid() == 'admin' ? true : false,
					// 	size: "small",
					// 	type: "primary",
					// 	icon: "el-icon-plus el-icon--left",
					// 	name: "添加",
					// 	action: "createShelf"
					// },
					{
						type: 'primary',
						size: 'small',
						icon: "el-icon-eleg-icon_table el-icon--left",
						name: "导出表格",
						action: "exportExcel"
					},
					{
						size: 'small',
						type: 'primary',
						icon: 'el-icon-eleg-icon_link el-icon--left',
						name: '绑定区域',
						action: 'bindDistrict'
					},
					{
						show: GloabFun.getUid() == 'admin' ? true : false,
						size: "small",
						type: "danger",
						icon: "el-icon-delete2 el-icon--left",
						name: "删除",
						action: "deleteShelf"
					}],
					currentPage: 1,
					pageSize: 10,
					createShelfForm: {
						tag: '',
						code: '',
						Desc: ''
					},
					createRules: {
						tag: [{
							required: true,
							message: "层架标签不能为空",
							trigger: 'blur'
						}],
						code: [{
							required: true,
							message: "层架编号不能为空",
							trigger: 'blur'
						}],
						Desc: [{
							required: true,
							message: "层架描述不能为空",
							trigger: 'blur'
						}],
					},
					multipleSelection: [],
					editShelfForm: {
						tag: '',
						code: '',
						Desc: ''
					}
				}

			},
			props: {
				templateObj: {
					type: Object,
					default: function() {
						return {};
					}
				}
			},
			methods: {
				executeAction(action) {
					if(action) {
						this[action]();
					}
				},
			//导出表格
			exportExcel() {　　　　　　
				require.ensure([], () => {　　　　　　　　
					const {
						export_json_to_excel
					} = require('../../../../assets/js/vendor/Export2Excel.js');　　　　　　　　
					const tHeader = ['编号', '条码', '描述', '创建时间', '备注'];　　　　　　　　
					const filterVal = ['code', 'tag', 'Desc', 'time', ''];　　　　　　　　
					const list = this.tableData;　　　　　　　　
					const data = this.formatJson(filterVal, list);　　　　　　　
					export_json_to_excel(tHeader, data, '层架信息');　　　　　　
				})　　　
			},
			formatJson(filterVal, jsonData) {　　　　　　
				return jsonData.map(v => filterVal.map(j => v[j]))　　
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDatas();
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.getDatas();
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			selectType() {
				if(this.value === 0) {
					this.contentHint = '层架编号 查询';
				} else if(this.value === 1) {
					this.contentHint = '层架标签 查询';
				} else {
					this.contentHint = '层架描述 查询';
				}
			},
			formateSelection() {
				var result = [],
				array = this.multipleSelection;
				for(var i = 0; i < array.length; i++) {
					result.push(array[i].keyID);
				}
				return result;
			},
			//创建层架
			createShelf() {
				this.createShelfDialog = true;
			},
			//确认创建层架
			confirmCreate(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						HttpServer.httpPost.call(this, '/Api/Inventory/Create/BookrackShelfTag', {
							info: [this.createShelfForm]
						}, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.createShelfDialog = false;
								this.$notify({
									title: '成功',
									message: this.$t('message.addSuccess'),
									type: 'success',
									duration: 2500
								});
								this.getDatas();
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					} else {
						return false;
					}
				});
			},
			//批量删除层架信息
			deleteShelf() {
				if(this.formateSelection().length > 0) {
					this.$confirm('此操作将删除所选层架信息，是否继续？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						HttpServer.httpPost.call(this, '/Api/Inventory/Delete/BookrackShelfTag', {
							keyid: this.formateSelection()
						}, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.getDatas();
								this.$notify({
									title: '成功',
									message: this.$t('message.deleteSuccess'),
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.operationCanceled'),
							duration: 2500
						})
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: this.$t('message.selectBulkDeleteWarning'),
						type: 'warning',
						duration: 2500
					});
				}
			},
			//修改层架信息
			editShelf(row) {
				// this.editShelfForm = row;
				this.editShelfForm.tag = row.tag;
				this.editShelfForm.code = row.code;
				this.editShelfForm.Desc = row.Desc;
				this.editShelfDialog = true;
			},
			//查看层架书籍信息
			shelfBook(row) {
				row.currentPage = this.currentPage;
				row.pageSize = this.pageSize;
				row.value = this.value;
				row.searchModel = this.searchModel;
				row.districtid = this.cascaderId;
				this.$emit('changeView', 'ShelfBookList', row);
			},
			setPosition(row){
				row.currentPage = this.currentPage;
				row.pageSize = this.pageSize;
				row.value = this.value;
				row.searchModel = this.searchModel;
				row.districtid = this.cascaderId;
				this.$emit('changeView','setMap',row);
			},
			//确认修改层架信息
			confirmEdit(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						HttpServer.httpPost.call(this, '/Api/Inventory/Update/BookrackShelfTag', this.editShelfForm, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.editShelfDialog = false;
								this.$notify({
									title: '成功',
									message: this.$t('message.saveSuccess'),
									type: 'success',
									duration: 2500
								});
								this.getDatas();
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					} else {
						return false;
					}
				})
			},
			sortDatas(arr) {
				for(var i=0;i<arr.length;i++){
					for(var j = i + 1;j<arr.length;j++){
						if(arr[i].DistrictKeyId>arr[j].DistrictKeyId){
							var tmp = arr[i];
							arr[i] = arr[j];
							arr[j] = tmp;
						}
					}
				}
				return arr;
			},
			//获取区域列表 -- 用于绑定时显示在弹窗上的
			getDistrictDatas() {
				HttpServer.httpGet.call(this, '/Api/District/districtTree?uid=' + parseInt(GloabFun.getKeyId()), function(response) {}, function(response) {
					// console.log('获取当前用户的所有绑定区域信息',response)
					if(response.data.code === 0) {
						if(response.data.info.length > 0) {
							this.districtsDatas = this.sortDatas(response.data.info);
							this.defaultExpandedKeys.push(this.districtsDatas[0].DistrictKeyId);
							this.currentNodeKey = this.districtsDatas[0].DistrictKeyId;
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			},
			handleNodeClick(data) {
				this.currentNodeKey = data.DistrictKeyId;
			},
			//绑定区域
			bindDistrict() {
				if(this.formateSelection().length > 0){
					this.getDistrictDatas();
					this.bindDistrictDialog = true;
				}else {
					this.$notify({
						title: this.$t('message.warning'),
						message: '请选择批量操作的项',
						type: 'warning',
						duration: 2500
					});
				}	
			},
			//绑定
			confirmBind() {
				this.$confirm('此操作将层架绑定至所选区域，是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					HttpServer.httpPost.call(this, '/Api/District/BindBookrackShelf', {
						keyid: parseInt(GloabFun.getKeyId()),
						districtid: this.currentNodeKey,
						shelfids: this.formateSelection(),
					}, function(response) {}, function(response) {
						if(response.data.code === 0) {
							this.$notify({
								title: '成功',
								message: '绑定成功',
								type: 'success',
								duration: 2500
							});
							this.getDatas();
						} else {
							this.$notify.error({
								title: '错误',
								message: response.data.msg,
								duration: 2500
							});
						}
					});
				}).catch(() => {
					this.$notify.info({
						title: '消息',
						message: this.$t('message.operationCanceled'),
						duration: 2500
					})
				});
			},
			traverseTree(node){
				for (var m = 0 ; m < node.length; m ++){
					if (node[m].Children && node[m].Children.length > 0) {
						var i = 0;
						this.traverseTree(node[m].Children);
					}else {
						node[m].Children = null;
					}
				}	
			},
			//获取区域列表
			getAllDistrictDatas() {
				HttpServer.httpGet.call(this, '/Api/District/districtTree?uid=' + parseInt(GloabFun.getKeyId()), function(response) {}, function(response) {
					// console.log('获取当前用户的所有绑定区域信息',response)
					if(response.data.code === 0) {
						if(response.data.info.length > 0) {
							if(GloabFun.getUid() === 'admin'){
								response.data.info.unshift({
									Name: '全部',
									DistrictKeyId: 0
								});
							}
							this.traverseTree(response.data.info);
							this.cascaderDatas = this.sortDatas(response.data.info);
							if(this.templateObj.tag && this.templateObj.tag != '') {
								this.cascaderId = this.templateObj.districtid;
							}else{
								this.cascaderId = [response.data.info[0].DistrictKeyId];
							}
							this.selectDistrictId = this.cascaderId[this.cascaderId.length - 1];
							this.getDatas();
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			},
			//选择区域
			selectDistrict() {
				this.selectDistrictId = this.cascaderId[this.cascaderId.length - 1];
				this.getDatas();
			},
			//刷新
			reloadDatas() {
				this.isReload = true;
				this.getDatas();
			},
			getDatas() {
				this.loading = true;
				var param = {
					districtid: this.selectDistrictId,
					tag: this.value === 1 ? this.searchModel : '',
					code: this.value === 0 ? this.searchModel : '',
					Desc: this.value === 2 ? this.searchModel : '',
					index: this.currentPage,
					pagesize: this.pageSize,
					UserId: parseInt(GloabFun.getKeyId())
				}
				HttpServer.httpPost.call(this, '/Api/Inventory/BookrackShelfTagList', param ,function(response) {}, function(response) {
						// console.log('层架信息', response);
						this.loading = false;
						if(response.data.code === 0) {
							this.tableData = response.data.info;
							this.totalSize = response.data.totalcount;
						} else {
							this.$notify.error({
								title: '错误',
								message: response.data.msg,
								duration: 2500
							});
						}
					});
			}
		},
		created() {
			if(this.templateObj.tag && this.templateObj.tag != '') {
				this.currentPage = this.templateObj.currentPage;
				this.pageSize = this.templateObj.pageSize;
				this.value = this.templateObj.value;
				this.searchModel = this.templateObj.searchModel;
			}
			this.getAllDistrictDatas();
		}
	}
</script>
<style scoped lang="less">
	.flex-inline {
		display: flex;
		justify-content: space-between;
		padding-bottom: 2px;
		.query {
			display: flex;
		}
	}
	
	.name {
		color: #20a0ff;
	}
	
	.edit-mission {
		padding-top: 50px;
		.el-dialog__header {
			background-color: #000;
		}
		.el-dialog__body {
			position: relative;
		}
		.clearfloat {
			height: 100px;
			max-height: 150px;
		}
	}
</style>